package com.lyf.boot.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import com.lyf.boot.base.system.dao.BaseLoginRecordDao;
import com.lyf.boot.base.system.entity.LoginRecord;
import com.lyf.boot.listener.event.LoginEvent;
import com.lyf.boot.utils.ServerUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author Luyufan
 * @date 2023/7/6 16:07
 */
@Component
@RequiredArgsConstructor
public class LoginEventListener {

    private final BaseLoginRecordDao baseLoginRecordDao;

    @Async
    @EventListener(LoginEvent.class)
    public void loginEventHandler(LoginEvent event){
        LoginRecord loginRecord = BeanUtil.copyProperties(event, LoginRecord.class);
        String userAgent = event.getUserAgent();
        UserAgent agent = UserAgentUtil.parse(userAgent);
        loginRecord.setBrowser(agent.getBrowser().getName());
        loginRecord.setOs(agent.getOs().getName());
        loginRecord.setCreateBy(event.getUserId());
        loginRecord.setUpdateBy(event.getUserId());
        loginRecord.setCreateTime(event.getLoginTime());
        loginRecord.setAddress(ServerUtil.getIpRegion(event.getIpAddr()));
        baseLoginRecordDao.insert(loginRecord);
    }
}
